﻿using System;

namespace MyLib {
	/// <summary>
	/// 
	/// </summary>
	class AutoTransaction : ITransaction {
		/// <summary>
		/// 
		/// </summary>
		public void Commit() {
			try {
				Transaction.Commit();
				Connection.Close();
			} catch {
			} finally {
				Transaction = null;
				Connection = null;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public void Rollback() {
			try {
				Transaction.Rollback();
				Connection.Close();
			} catch {
			} finally {
				Transaction = null;
				Connection = null;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public void Close() {
			if (Transaction != null) {
				Rollback();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public void Dispose() {
			Close();
		}

		/// <summary>
		/// 
		/// </summary>
		public System.Data.Common.DbConnection Connection {
			get;
			private set;
		}

		/// <summary>
		/// 
		/// </summary>
		public System.Data.Common.DbTransaction Transaction {
			get;
			private set;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="connection"></param>
		/// <param name="transaction"></param>
		public AutoTransaction(System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction) {
			System.Diagnostics.Debug.Assert(connection != null);
			System.Diagnostics.Debug.Assert(connection.State == System.Data.ConnectionState.Open);
			System.Diagnostics.Debug.Assert(transaction != null);

			Connection = connection;
			Transaction = transaction;
		}

		/// <summary>
		/// 
		/// </summary>
		public bool Closed {
			get { return Connection == null || Connection.State == System.Data.ConnectionState.Closed; }
		}
	} // end of AutoTransaction.
}
